<template>
  <div>
    <!-- 顶部 -->
    <van-nav-bar :fixed="true" placeholder>
      <template #left>
        <img src="../../assets/toutiao_logo.png" alt="" />
      </template>
      <template #right>
        <van-icon name="search" size="0.48rem" @click="searchFn" />
      </template>
    </van-nav-bar>
    <!-- 导航 -->
    <van-tabs
      class="tabs_bottom"
      v-model="active"
      offset-top="1.2666667rem"
      animated
      sticky
      @change="tabsChangeFn"
      :before-change="beforeChangeChannelFn"
    >
      <van-tab
        v-for="obj in channelList"
        :key="obj.id"
        :title="obj.name"
        :name="obj.id"
      >

        <!-- 文章内容 -->
        <article-list :channelId="active"></article-list>
      </van-tab>
    </van-tabs>
    <van-action-sheet
      class="actionSheet"
      :cancel-text="cancelText"
      v-model="$store.state.actionSheetModel"
      :actions="actionsList"
      @select="onSelect"
      @cancel="onCancle"
      get-container="body"
    />
    <van-icon name="plus" size="0.37333334rem" class="moreChannels" @click="popupShowFn"/>
    <van-popup v-model="show" class="editChannel-warp">
      <EditChannelList @closePopup="closePopupFn"
      @addChannelEvent="addChannelFn"
      @delChannelEvent="delChannelFn"
      :channelList="channelList"
      v-model="active"
      ></EditChannelList>
    </van-popup>
  </div>
</template>

<script>
import ArticleList from './ArticleList.vue'
import { getUserArticleList, dislikeArticleAPI, reportArticleAPI, setChannelListAPI, delChannelAPI } from '@/api'
import { mapState, mapMutations } from 'vuex'
import EditChannelList from './EditChannelList.vue'

const nameToTop = {}
export default {
  components: {
    ArticleList,
    EditChannelList
  },
  data () {
    return {
      show: false,
      active: 0,
      channelList: [],
      actionsList: [],
      cancelText: '取消'
    }
  },
  computed: {
    ...mapState([
      'actionSheetModel',
      'firstActionSheet',
      'secondActionSheet',
      'artIdActions'
    ])
  },

  methods: {
    ...mapMutations(['changeActionSheetModelMutations']),
    async onSelect (item) {
      // 默认情况下点击选项时不会自动收起
      // 可以通过 close-on-click-action 属性开启自动收起
      if (item.name === '反馈垃圾内容') {
        // console.log(item)
        this.actionsList = this.secondActionSheet
        this.cancelText = '返回'
      } else if (item.name === '不感兴趣') {
        // 向后台发送请求
        await dislikeArticleAPI(this.artIdActions)
        this.$notify({ type: 'success', message: '标记成功' })
        // 关闭反馈面板
        this.changeActionSheetModelMutations(false)
      } else {
        // console.log(this.artIdActions)
        await reportArticleAPI({
          artId: this.artIdActions,
          type: item.value
        })
        this.$notify({ type: 'success', message: '举报成功' })
        this.changeActionSheetModelMutations(false)
        setTimeout(() => {
          this.actionsList = this.firstActionSheet
        }, 300)
      }
    },
    onCancle () {
      // console.log(item)
      // cancel 点击取消按钮时触发
      // 判断，如果是点击的返回，就将值改为一级面板的值
      if (this.cancelText === '返回') {
        this.actionsList = this.firstActionSheet
        this.cancelText = '取消'
        this.changeActionSheetModelMutations(true)
      }
      // 同时页面依旧显示
    },
    popupShowFn () {
      this.show = true
    },
    closePopupFn (val) {
      this.show = val
    },
    // 添加频道
    async addChannelFn (addObj) {
      if (addObj.id !== 0) {
        this.channelList.push(addObj)
        // console.log(this.channelList)
        const newArr = []
        this.channelList.forEach((obj, index) => {
          const newObj = { ...obj }
          newObj.seq = index + ''
          delete newObj.name
          newArr.push(newObj)
        })
        // console.log(newArr)
        await setChannelListAPI(newArr)
      }
      // console.log(res)
    },
    // 删除频道
    async delChannelFn (channelId) {
      await delChannelAPI(channelId)
      // console.log(res)
      const index = this.channelList.findIndex(obj => obj.id === channelId)
      this.channelList.splice(index, 1)
    },
    searchFn () {
      this.$router.push('/search')
    },
    // 在切换频道之前，执行的方法
    beforeChangeChannelFn () {
      // 将当前页面滚动条滚动的位置，赋值给变量  nameToTop[this.active]   其中的 this.active 指的是高亮的那个频道
      nameToTop[this.active] = document.documentElement.scrollTop
      console.log(nameToTop)
      // 返回值为 true 频道切换才可以跳转
      return true
    },
    // 点击切换频道时，执行的方法
    tabsChangeFn () {
      // 切换tab 栏的DOM更新是异步的 ，等到DOM更新完成，在执行滚动（滚动到之前所在的位置）
      setTimeout(() => {
        document.documentElement.scrollTop = nameToTop[this.active]
      }, 0)
    }
  },
  async created () {
    const res = await getUserArticleList()
    this.channelList = res.data.data.channels
    this.actionsList = this.firstActionSheet
    // 在路由中添加meta{scrollT : 0} , scrollT用来存储窗口滚动条滚动的位置
    // 监听窗口滚动的事件，将窗口滚动的位置保存到路由   this.$route.meta.scrollT   中
    window.addEventListener('scroll', () => {
      this.$route.meta.scrollT = document.documentElement.scrollTop
      // console.log(this.$route.meta.scrollT)
    })
  },
  activated () {
    // 当页面被激活的时候，将 scrollT 中保存的位置，重新赋值给这个页面
    document.documentElement.scrollTop = this.$route.meta.scrollT
  },
  deactivated () {
    this.$store.state.actionSheetModel = false
  }
}
</script>

<style lang="less" scoped>
/deep/ .van-nav-bar__left img {
  width: 100px;
  height: 30px;
}
/deep/ .van-icon-search {
  color: white;
}
/deep/ .tabs_bottom {
  padding-bottom: 46px;
}
// 设置 tabs 容器的样式
/deep/ .van-tabs__wrap {
  padding-right: 30px;
  background-color: #fff;
}

// 设置小图标的样式
.moreChannels {
  position: fixed;
  top: 62px;
  right: 8px;
  z-index: 999;
}

.editChannel-warp{
  background-color: transparent;
  height: 100%;
  width: 100%;
  background-color: #fff;
}

.popup-container {
  display: flex;
  flex-direction: column;
}
</style>
